<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频播放平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://vjs.zencdn.net/8.3.0/video-js.css" rel="stylesheet">
    <link href="https://unpkg.com/@videojs/themes@1/dist/forest/index.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2FB3FF;    /* 腾讯视频主色调-天蓝色 */
            --secondary-color: #1A90E6;  /* 深天蓝色 */
            --accent-color: #00C6FF;     /* 亮蓝色 */
            --gradient-start: #2FB3FF;   
            --gradient-end: #1A90E6;     
            --text-color: #2C2C2C;      /* 深灰色文字 */
            --light-bg: #F7F7F7;        /* 浅灰背景 */
            --card-bg: #FFFFFF;         
            --success-color: #11B17C;    /* 绿色 */
            --warning-color: #FF9C1B;    /* 橙色 */
            --danger-color: #FF4B4B;     /* 红色 */
        }

        body {
            background-color: var(--light-bg);
            color: var(--text-color);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .header {
            background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(124, 58, 237, 0.15);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-weight: 600;
            margin: 0;
            font-size: 2rem;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-custom {
            padding: 0.5rem 1.5rem;
            border-radius: 8px;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .btn-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .btn-upload {
            background: linear-gradient(to right, #2FB3FF, #1A90E6);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
        }

        .btn-upload:hover {
            background: linear-gradient(to right, #1A90E6, #2FB3FF);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(47, 179, 255, 0.3);
        }

        .category-filter {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }

        .form-select {
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            padding: 0.75rem;
            font-size: 1rem;
        }

        .video-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1.5rem;
            padding: 1rem;
        }

        .video-card {
            background: var(--card-bg);
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .video-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 12px 20px rgba(47, 179, 255, 0.1);
        }

        .video-thumbnail-container {
            position: relative;
            width: 100%;
            padding-top: 56.25%;
            overflow: hidden;
            border-radius: 8px 8px 0 0;
            background: linear-gradient(45deg, #2FB3FF, #1A90E6);
        }

        .video-thumbnail {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            filter: brightness(0.95);
        }

        .video-card:hover .video-thumbnail {
            transform: scale(1.08);
            filter: brightness(1.05);
        }

        .play-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(
                to bottom,
                rgba(47, 179, 255, 0.1),
                rgba(26, 144, 230, 0.4)
            );
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.4s ease;
        }

        .play-overlay i {
            color: white;
            font-size: 3.5rem;
            transform: scale(0.8);
            transition: all 0.4s ease;
            filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.2));
        }

        .video-card:hover .play-overlay {
            opacity: 1;
        }

        .video-card:hover .play-overlay i {
            transform: scale(1);
        }

        .video-info {
            padding: 1.25rem;
            background: linear-gradient(
                to bottom,
                rgba(255, 255, 255, 0.8),
                rgba(255, 255, 255, 1)
            );
        }

        .video-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--text-color);
            margin-bottom: 0.75rem;
            line-height: 1.5;
        }

        .video-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            font-size: 0.9rem;
            color: #6B7280;
        }

        .video-meta span {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .video-meta i {
            color: var(--accent-color);
            font-size: 1rem;
        }

        /* 视频播放器容器样式 */
        #videoPlayerContainer {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .video-player-info {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid #eee;
        }

        .video-player-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: var(--text-color);
        }

        .video-player-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
            color: #666;
        }

        .video-player-description {
            background: var(--light-bg);
            padding: 1rem;
            border-radius: 8px;
            color: #666;
            line-height: 1.6;
        }

        .modal-content {
            border-radius: 12px;
            overflow: hidden;
        }

        .modal-header {
            background: linear-gradient(135deg, #4361ee, #3f37c9);
            color: white;
            border-bottom: 1px solid #eee;
            padding: 1.5rem;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }

        .modal-body {
            padding: 2rem;
        }

        .form-label {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }

        .form-control {
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            padding: 0.75rem;
        }

        .progress {
            height: 8px;
            border-radius: 4px;
            margin-top: 1rem;
        }

        .progress-bar {
            background-color: var(--accent-color);
            transition: width 0.3s ease;
        }

        @media (max-width: 768px) {
            .header {
                padding: 1.5rem 0;
            }

            .header h1 {
                font-size: 1.5rem;
            }

            .video-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 1rem;
            }
        }

        /* 加载动画 */
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid var(--light-bg);
            border-top: 5px solid var(--accent-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 2rem auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空状态提示 */
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #666;
        }

        .empty-state i {
            font-size: 4rem;
            color: var(--accent-color);
            margin-bottom: 1rem;
        }

        /* 上传进度提示 */
        .upload-progress {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            background: white;
            padding: 1rem;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1000;
            min-width: 300px;
        }

        .upload-progress.hide {
            display: none;
        }

        /* 更新分类导航样式 */
        .category-nav {
            background: var(--card-bg);
            padding: 1rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .category-list {
            display: flex;
            flex-wrap: nowrap;
            overflow-x: auto;
            gap: 1rem;
            padding: 0 1rem;
            scrollbar-width: none;  /* Firefox */
            -ms-overflow-style: none;  /* IE and Edge */
        }

        .category-list::-webkit-scrollbar {
            display: none;  /* Chrome, Safari, Opera */
        }

        .category-item {
            padding: 0.5rem 1.25rem;
            border-radius: 20px;
            background: transparent;
            color: #666;
            cursor: pointer;
            white-space: nowrap;
            transition: all 0.3s ease;
            border: 1px solid #eee;
        }

        .category-item:hover {
            color: var(--primary-color);
            border-color: var(--primary-color);
            background: rgba(47, 179, 255, 0.05);
        }

        .category-item.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
    </style>
</head>
<body>
    <!-- 页头 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <h1>视频播放平台</h1>
                <div class="header-actions">
                    <!-- 登录前显示 -->
                    <div id="loginButton">
                        <button class="btn btn-custom btn-outline-light" data-bs-toggle="modal" data-bs-target="#loginModal">
                            <i class="fas fa-sign-in-alt"></i> 登录
                        </button>
                    </div>
                    
                    <!-- 登录后显示 -->
                    <div id="userInfo" style="display: none;">
                        <div class="d-flex align-items-center gap-3">
                            <span class="text-white">
                                <i class="fas fa-user"></i> 
                                <span id="currentUser"></span>
                            </span>
                            <button id="uploadBtn" class="btn btn-custom btn-upload" style="display: none;">
                                <i class="fas fa-upload"></i> 上传视频
                            </button>
                            <button class="btn btn-custom btn-outline-light" onclick="logout()">
                                <i class="fas fa-sign-out-alt"></i> 退出
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="container">
        <!-- 分类导航 -->
        <nav class="category-nav">
            <div class="container">
                <div class="category-list">
                    <div class="category-item active" data-category="">全部</div>
                    <!-- 分类项将通过 JavaScript 动态添加 -->
                </div>
            </div>
        </nav>

        <!-- 视频播放器容器 -->
        <div id="videoPlayerContainer" style="display: none;" class="mb-4">
            <video
                id="videoPlayer"
                class="video-js vjs-theme-forest vjs-big-play-centered"
                controls
                preload="auto"
                width="100%"
                poster="/images/thumbnails/default.jpg"
                data-setup="{}"
            >
                <p class="vjs-no-js">
                    要观看此视频，请启用 JavaScript，并考虑升级到支持 HTML5 视频的浏览器
                </p>
            </video>
            <div class="video-player-info">
                <h2 id="videoTitle" class="video-player-title"></h2>
                <div class="video-player-meta">
                    <span><i class="fas fa-folder"></i> <span id="videoCategory"></span></span>
                    <span><i class="fas fa-calendar"></i> <span id="videoUploadTime"></span></span>
                    <span><i class="fas fa-eye"></i> <span id="videoViews"></span> 次观看</span>
                </div>
                <div class="video-player-description" id="videoDescription"></div>
            </div>
        </div>

        <!-- 视频列表 -->
        <div class="video-grid" id="videoList">
            <!-- 视频卡片将通过 JavaScript 动态添加 -->
        </div>

        <!-- 加载动画 -->
        <div class="loading-spinner" id="loadingSpinner" style="display: none;"></div>

        <!-- 空状态提示 -->
        <div class="empty-state" id="emptyState" style="display: none;">
            <i class="fas fa-video-slash"></i>
            <h3>暂无视频</h3>
            <p>当前分类下还没有视频，快来上传第一个视频吧！</p>
        </div>
    </main>

    <!-- 登录模态框 -->
    <div class="modal fade" id="loginModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">用户登录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="loginForm">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" required>
                        </div>
                        <button type="submit" class="btn btn-custom btn-upload w-100">登录</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 上传模态框 -->
    <div class="modal fade" id="uploadModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传视频</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm">
                        <div class="mb-3">
                            <label for="videoFile" class="form-label">选择视频文件</label>
                            <input type="file" class="form-control" id="videoFile" accept="video/*" required>
                        </div>
                        <div class="mb-3">
                            <label for="videoTitle" class="form-label">视频标题</label>
                            <input type="text" class="form-control" id="videoTitle" required>
                        </div>
                        <div class="mb-3">
                            <label for="videoCategory" class="form-label">视频分类</label>
                            <select class="form-select" id="videoCategory" required>
                                <option value="" disabled selected>请选择分类</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="videoDescription" class="form-label">视频描述</label>
                            <textarea class="form-control" id="videoDescription" rows="3"></textarea>
                        </div>
                        <button type="submit" class="btn btn-custom btn-upload w-100">开始上传</button>
                    </form>
                    <div class="progress mt-3" style="display: none;">
                        <div class="progress-bar" role="progressbar"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 上传进度提示 -->
    <div class="upload-progress hide" id="uploadProgress">
        <h6 class="mb-2">正在处理视频...</h6>
        <div class="progress">
            <div class="progress-bar" role="progressbar"></div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Video.js -->
    <script src="https://vjs.zencdn.net/8.3.0/video.min.js"></script>
    <!-- HLS.js (用于 HLS 流播放) -->
    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

    <script>
    let player = null;
    let isLoggedIn = false;
    let currentUser = null;
    let currentPage = 0;
    let pageSize = 12;

    // 文档加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化应用
        initializeApp();
    });

    // 应用初始化函数
    function initializeApp() {
        // 检查登录状态
        checkLoginStatus()
            .then(() => {
                console.log('Login status checked');
                return Promise.all([
                    loadCategories(),
                    loadVideos()
                ]);
            })
            .catch(error => {
                console.log('Error during initialization:', error);
                // 即使登录检查失败，也加载基本功能
                return Promise.all([
                    loadCategories(),
                    loadVideos()
                ]);
            });
    }

    // 加载视频列表
    function loadVideos(category = '') {
        const url = category ? 
            `/api/videos/list/${encodeURIComponent(category)}?page=${currentPage}&size=${pageSize}` :
            `/api/videos/list?page=${currentPage}&size=${pageSize}`;

        fetch(url)
            .then(response => response.json())
            .then(videos => {
                const videoList = document.getElementById('videoList');
                videoList.innerHTML = ''; // 清空现有内容
                
                if (videos.length === 0) {
                    // 显示空状态
                    videoList.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-video-slash"></i>
                            <h3>暂无视频</h3>
                            <p>${category ? `当前分类"${category}"下还没有视频` : '还没有任何视频'}，快来上传第一个视频吧！</p>
                        </div>
                    `;
                } else {
                    videos.forEach(video => {
                        videoList.appendChild(createVideoCard(video));
                    });
                }
            })
            .catch(error => console.error('Error loading videos:', error));
    }

    // 创建视频卡片
    function createVideoCard(video) {
        const card = document.createElement('div');
        card.className = 'video-card';
        card.innerHTML = `
            <div class="video-thumbnail-container">
                <img src="${video.thumbnailUrl || '/images/thumbnails/default.jpg'}" 
                     class="video-thumbnail" 
                     alt="${video.title}"
                     onerror="this.src='/images/thumbnails/default.jpg'">
                <div class="play-overlay">
                    <i class="fas fa-play-circle"></i>
                </div>
            </div>
            <div class="video-info">
                <div class="video-title">${video.title}</div>
                <div class="video-meta">
                    <span>
                        <i class="fas fa-folder"></i>
                        ${video.category}
                    </span>
                    <span>
                        <i class="fas fa-eye"></i>
                        ${video.views || 0} 次观看
                    </span>
                </div>
            </div>
        `;
        card.onclick = () => window.location.href = `/play.html?id=${video.id}`;
        return card;
    }

    // 播放视频
    function playVideo(video) {
        const playerContainer = document.getElementById('videoPlayerContainer');
        playerContainer.style.display = 'block';
        
        // 更新视频信息
        document.getElementById('videoTitle').textContent = video.title;
        document.getElementById('videoCategory').textContent = video.category;
        document.getElementById('videoUploadTime').textContent = formatDate(video.uploadTime);
        document.getElementById('videoViews').textContent = video.views || 0;
        document.getElementById('videoDescription').textContent = video.description || '暂无描述';

        // 滚动到播放器位置
        playerContainer.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });

        // 加载视频
        fetch(`/api/videos/hls/${video.fileName}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('视频加载失败');
                }
                return response.text();
            })
            .then(hlsUrl => {
                if (player) {
                    player.src({
                        src: hlsUrl,
                        type: 'application/x-mpegURL'
                    });
                    player.play().catch(e => {
                        console.warn('Autoplay prevented:', e);
                    });
                } else {
                    console.error('Video player not initialized');
                }
            })
            .catch(error => {
                console.error('Error loading video:', error);
                alert('视频加载失败，请稍后重试');
            });
    }

    // 加载分类列表
    function loadCategories() {
        // 加载导航栏分类
        fetch('/api/videos/categories')
            .then(response => response.json())
            .then(categories => {
                const categoryList = document.querySelector('.category-list');
                categories.forEach(category => {
                    const categoryItem = document.createElement('div');
                    categoryItem.className = 'category-item';
                    categoryItem.textContent = category;
                    categoryItem.dataset.category = category;
                    categoryItem.onclick = () => {
                        // 更新选中状态
                        document.querySelectorAll('.category-item').forEach(item => {
                            item.classList.remove('active');
                        });
                        categoryItem.classList.add('active');
                        // 加载对应分类的视频
                        currentPage = 0;
                        loadVideos(category);
                    };
                    categoryList.appendChild(categoryItem);
                });

                // 同时更新上传模态框的分类选项
                updateUploadCategories(categories);
            })
            .catch(error => console.error('Error loading categories:', error));
    }

    // 更新上传模态框的分类选项
    function updateUploadCategories(categories) {
        const select = document.getElementById('videoCategory');
        if (select) {
            // 清空现有选项
            select.innerHTML = '';
            
            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择分类';
            defaultOption.disabled = true;
            defaultOption.selected = true;
            select.appendChild(defaultOption);
            
            // 添加分类选项
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                select.appendChild(option);
            });

            console.log('Categories updated:', categories);
        } else {
            console.error('Category select element not found');
        }
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 修改分类选择事件处理
    function initializeCategoryFilter() {
        const categoryFilter = document.getElementById('categoryFilter');
        if (categoryFilter) {
            categoryFilter.addEventListener('change', function(e) {
                currentPage = 0;
                loadVideos(e.target.value);
            });
        }
    }

    // 更新已登录用户的 UI
    function updateUIForLoggedInUser() {
        const userInfo = document.getElementById('userInfo');
        const loginButton = document.getElementById('loginButton');
        const uploadBtn = document.getElementById('uploadBtn');
        
        if (userInfo && loginButton) {
            if (isLoggedIn && currentUser) {
                userInfo.style.display = 'block';
                loginButton.style.display = 'none';
                
                const currentUserSpan = document.getElementById('currentUser');
                if (currentUserSpan) {
                    currentUserSpan.textContent = currentUser.username;
                }
                
                if (uploadBtn) {
                    uploadBtn.style.display = currentUser.role === 'ADMIN' ? 'inline-block' : 'none';
                }
            } else {
                userInfo.style.display = 'none';
                loginButton.style.display = 'block';
                if (uploadBtn) {
                    uploadBtn.style.display = 'none';
                }
            }
        }
    }

    // 处理登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify({ username, password })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Login failed');
                }
                return response.json();
            })
            .then(user => {
                currentUser = user;
                isLoggedIn = true;
                const loginModal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
                if (loginModal) {
                    loginModal.hide();
                }
                updateUIForLoggedInUser();
                console.log('Login successful:', user);
            })
            .catch(error => {
                console.error('Login error:', error);
                alert('登录失败，请检查用户名和密码');
            });
        });
    }

    // 退出登录
    function logout() {
        fetch('/api/auth/logout', {
            method: 'POST'
        })
        .then(() => {
            isLoggedIn = false;
            currentUser = null;
            updateUIForLoggedOutUser();
        })
        .catch(error => {
            console.error('Logout error:', error);
            alert('退出登录失败');
        });
    }

    // 处理视频上传
    function uploadVideo() {
        if (!isLoggedIn) {
            alert('请先登录');
            return;
        }

        const videoCategory = document.getElementById('videoCategory');
        if (!videoCategory || !videoCategory.value) {
            alert('请选择视频分类');
            return;
        }

        const videoTitle = document.getElementById('videoTitle');
        if (!videoTitle || !videoTitle.value.trim()) {
            alert('请输入视频标题');
            return;
        }

        const file = document.getElementById('videoFile').files[0];
        if (!file) {
            alert('请选择要上传的视频文件');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', videoTitle.value.trim());
        formData.append('category', videoCategory.value);
        formData.append('description', document.getElementById('videoDescription').value.trim() || '');

        const progressBar = document.querySelector('.progress');
        const progressBarInner = progressBar.querySelector('.progress-bar');
        progressBar.style.display = 'block';

        fetch('/api/videos/upload', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(response.status === 401 ? '认证已过期，请重新登录' : 
                              response.status === 403 ? '没有上传权限' : '上传失败');
            }
            return response.json();
        })
        .then(video => {
            const uploadModal = bootstrap.Modal.getInstance(document.getElementById('uploadModal'));
            uploadModal.hide();
            document.getElementById('uploadForm').reset();
            progressBar.style.display = 'none';
            loadVideos(video.category);  // 重新加载当前分类的视频
            alert('视频上传成功！');
        })
        .catch(error => {
            console.error('Upload error:', error);
            progressBar.style.display = 'none';
            alert(error.message || '视频上传失败，请重试');
            if (error.message === '认证已过期，请重新登录') {
                isLoggedIn = false;
                currentUser = null;
                updateUIForLoggedOutUser();
                showLoginModal();
            }
        });
    }

    // 监听上传按钮点击事件
    const uploadBtn = document.getElementById('uploadBtn');
    if (uploadBtn) {
        uploadBtn.addEventListener('click', function() {
            // 确保分类已加载
            fetch('/api/videos/categories')
                .then(response => response.json())
                .then(categories => {
                    updateUploadCategories(categories);
                    const uploadModal = new bootstrap.Modal(document.getElementById('uploadModal'));
                    uploadModal.show();
                })
                .catch(error => {
                    console.error('Error loading categories:', error);
                    alert('加载分类失败，请重试');
                });
        });
    }

    // 监听上传表单提交
    const uploadForm = document.getElementById('uploadForm');
    if (uploadForm) {
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            uploadVideo();
        });
    }

    // 添加页面卸载时的清理
    window.addEventListener('beforeunload', function() {
        if (player) {
            player.dispose();
            player = null;
        }
    });

    // 添加滚动处理
    document.addEventListener('DOMContentLoaded', function() {
        const categoryNav = document.querySelector('.category-nav');
        const categoryList = document.querySelector('.category-list');
        
        // 添加鼠标滚轮横向滚动
        categoryList.addEventListener('wheel', (e) => {
            if (e.deltaY !== 0) {
                e.preventDefault();
                categoryList.scrollLeft += e.deltaY;
            }
        });

        // 处理粘性导航栏
        let lastScrollTop = 0;
        window.addEventListener('scroll', () => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            if (scrollTop > lastScrollTop) {
                categoryNav.style.transform = 'translateY(-100%)';
            } else {
                categoryNav.style.transform = 'translateY(0)';
            }
            lastScrollTop = scrollTop;
        });
    });

    // 在 initializeApp 函数后添加 checkLoginStatus 函数
    function checkLoginStatus() {
        return fetch('/api/auth/status', {
            credentials: 'include',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Status check failed');
            }
            return response.json();
        })
        .then(user => {
            if (user && user.username) {
                isLoggedIn = true;
                currentUser = user;
                updateUIForLoggedInUser();
                console.log('User is logged in:', user);
            } else {
                throw new Error('Invalid user data');
            }
        })
        .catch(error => {
            console.log('Not logged in or error:', error.message);
            isLoggedIn = false;
            currentUser = null;
            updateUIForLoggedInUser();
            return Promise.reject(error);
        });
    }

    // 添加显示登录模态框的函数
    function showLoginModal() {
        const loginModal = new bootstrap.Modal(document.getElementById('loginModal'));
        loginModal.show();
    }

    // 添加更新未登录用户 UI 的函数
    function updateUIForLoggedOutUser() {
        const userInfo = document.getElementById('userInfo');
        const loginButton = document.getElementById('loginButton');
        const uploadBtn = document.getElementById('uploadBtn');
        
        if (userInfo && loginButton) {
            userInfo.style.display = 'none';
            loginButton.style.display = 'block';
        }
        
        if (uploadBtn) {
            uploadBtn.style.display = 'none';
        }
    }
    </script>
</body>
</html> 